<template>
  <div class="orders-container">
    <div class="header">
      <h1>订单管理</h1>
    </div>
    
    <div class="content">
      <div class="orders-table">
        <table>
          <thead>
            <tr>
              <th>订单号</th>
              <th>客户</th>
              <th>金额</th>
              <th>状态</th>
              <th>退款状态</th>
              <th>下单时间</th>
              <th>操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="order in orders" :key="order.orderId">
              <td>#{{ order.orderId }}</td>
              <td>{{ order.userId }}</td>
              <td>¥{{ order.finalTotal != null ? order.finalTotal : order.orderTotal }}</td>
              <td>
                <span :class="['status', 'status-' + order.orderState]">
                  {{ getStatusText(order) }}
                </span>
              </td>
              <td>{{ getRefundStatusText(order) }}</td>
              <td>{{ order.orderDate }}</td>
              <td class="actions">
                <button @click="viewOrder(order)" class="action-btn">查看</button>
                <!-- 当订单处于退款申请中(refundStatus === 1)时，显示同意/拒绝退款按钮 -->
                <button
                  v-if="order.refundStatus === 1"
                  @click="approveRefund(order)"
                  class="action-btn action-approve"
                >
                  同意退款
                </button>
                <button
                  v-if="order.refundStatus === 1"
                  @click="rejectRefund(order)"
                  class="action-btn action-reject"
                >
                  拒绝退款
                </button>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'Orders',
  data() {
    return {
      orders: [],
      loading: false
    }
  },
  mounted() {
    this.loadOrders()
  },
  methods: {
    async loadOrders() {
      try {
        const businessId = this.$store.state.businessId
        if (!businessId) {
          this.$router.push('/login')
          return
        }

        this.loading = true
        const response = await this.$axios.post('/elm/BusinessManagementController/getOrderList', null, {
          params: { businessId }
        })

        if (response.data && (response.data.code === 200 || response.data.code === '200')) {
          this.orders = (response.data.result || []).slice().sort((a, b) => {
            const aTime = a && a.orderDate ? new Date(a.orderDate).getTime() : 0
            const bTime = b && b.orderDate ? new Date(b.orderDate).getTime() : 0
            return bTime - aTime
          })
        } else {
          console.error('获取订单列表失败:', response.data?.message)
        }
      } catch (error) {
        console.error('加载订单失败:', error)
      } finally {
        this.loading = false
      }
    },

    getStatusText(order) {
      // 如果订单已标记退款成功（orderState=4 且 refundStatus=2），优先显示"已退款"
      if (order && order.orderState === 4 && order.refundStatus === 2) {
        return '已退款'
      }
      const statusMap = {
        0: '待支付',
        1: '已支付',
        2: '配送中',
        3: '已完成',
        4: '已取消'
      }
      return statusMap[order?.orderState] || '未知'
    },

    getRefundStatusText(order) {
      const status = order && order.refundStatus
      const map = {
        0: '无',
        1: '申请中',
        2: '已退款',
        3: '已拒绝'
      }
      if (status === undefined || status === null) {
        return '无'
      }
      return map[status] || '无'
    },

    viewOrder(order) {
      alert('查看订单: #' + order.orderId)
    },

    async updateOrderStatus(order, newStatus) {
      try {
        const response = await this.$axios.post('/elm/BusinessManagementController/updateOrderStatus', null, {
          params: {
            orderId: order.orderId,
            status: newStatus
          }
        })

        if (response.data && (response.data.code === 200 || response.data.code === '200')) {
          order.orderState = newStatus
          alert('订单状态更新成功')
        } else {
          alert('状态更新失败: ' + (response.data?.message || '未知错误'))
        }
      } catch (error) {
        console.error('更新订单状态失败:', error)
        alert('状态更新失败')
      }
    },

    // 商家同意退款
    async approveRefund(order) {
      if (!confirm('确定要同意该订单的退款申请吗？')) return
      try {
        const response = await this.$axios.post('/elm/BusinessManagementController/approveRefund', null, {
          params: { orderId: order.orderId }
        })
        if (response.data && (response.data.code === 200 || response.data.code === '200')) {
          // 标记为已退款
          order.orderState = 4
          order.refundStatus = 2
          alert('已同意退款并处理完成')
        } else {
          alert('同意退款失败: ' + (response.data?.message || '未知错误'))
        }
      } catch (error) {
        console.error('同意退款失败:', error)
        alert('同意退款失败，请稍后重试')
      }
    },

    // 商家拒绝退款
    async rejectRefund(order) {
      const reason = window.prompt('请输入拒绝退款的原因（可选）：', '')
      if (reason === null) return
      try {
        const response = await this.$axios.post('/elm/BusinessManagementController/rejectRefund', null, {
          params: {
            orderId: order.orderId,
            reason: reason || ''
          }
        })
        if (response.data && (response.data.code === 200 || response.data.code === '200')) {
          order.refundStatus = 3
          order.refundReason = reason || order.refundReason
          alert('已拒绝退款申请')
        } else {
          alert('拒绝退款失败: ' + (response.data?.message || '未知错误'))
        }
      } catch (error) {
        console.error('拒绝退款失败:', error)
        alert('拒绝退款失败，请稍后重试')
      }
    }
  }
}
</script>

<style scoped>
.orders-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #f5f5f5;
}

.header {
  background: white;
  padding: 20px 30px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
}

.header h1 {
  margin: 0;
  font-size: 24px;
  color: #333;
}

.content {
  flex: 1;
  overflow-y: auto;
  padding: 30px;
}

.orders-table {
  background: white;
  border-radius: 10px;
  overflow: hidden;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
}

table {
  width: 100%;
  border-collapse: collapse;
}

thead {
  background-color: #f5f5f5;
}

th {
  padding: 15px;
  text-align: left;
  font-weight: 600;
  color: #333;
  border-bottom: 2px solid #eee;
}

td {
  padding: 15px;
  border-bottom: 1px solid #eee;
}

.status {
  display: inline-block;
  padding: 4px 12px;
  border-radius: 20px;
  font-size: 12px;
  font-weight: 600;
}

.status-0 { background-color: #fff3e0; color: #f57c00; }
.status-1 { background-color: #e3f2fd; color: #1976d2; }
.status-2 { background-color: #f3e5f5; color: #7b1fa2; }
.status-3 { background-color: #d4edda; color: #155724; }
.status-4 { background-color: #f8d7da; color: #721c24; }

.actions {
  display: flex;
  gap: 8px;
}

.action-btn {
  padding: 6px 12px;
  background-color: #e3f2fd;
  color: #1976d2;
  border: none;
  border-radius: 4px;
  font-size: 12px;
  cursor: pointer;
  transition: all 0.3s;
}

.action-btn.action-approve {
	background-color: #e8f5e9;
	color: #2e7d32;
}

.action-btn.action-approve:hover {
	background-color: #c8e6c9;
}

.action-btn.action-reject {
	background-color: #ffebee;
	color: #c62828;
}

.action-btn.action-reject:hover {
	background-color: #ffcdd2;
}

.action-btn:hover {
  background-color: #bbdefb;
}
</style>
